package com.gitee.qdbp.vmall.sales.biz.goods.manage.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.result.ResultCode;
import com.gitee.qdbp.base.system.model.IAccount;
import com.gitee.qdbp.general.common.api.reusable.model.SimpleTreeBean;
import com.gitee.qdbp.general.common.api.reusable.service.ISimpleTreeQueryer;
import com.gitee.qdbp.tools.codec.CodeTools;
import com.gitee.qdbp.tools.specialized.KeywordHandler;
import com.gitee.qdbp.tools.utils.VerifyTools;
import com.gitee.qdbp.vmall.sales.api.goods.main.model.GoodsVersionBean;
import com.gitee.qdbp.vmall.sales.api.goods.manage.model.ShoppingCartBean;
import com.gitee.qdbp.vmall.sales.api.goods.manage.model.ShoppingCartUpdate;
import com.gitee.qdbp.vmall.sales.api.goods.manage.model.ShoppingCartWhere;
import com.gitee.qdbp.vmall.sales.api.goods.manage.model.ShoppingGoodsItem;
import com.gitee.qdbp.vmall.sales.api.goods.manage.service.IShoppingCartExecutor;
import com.gitee.qdbp.vmall.sales.api.specific.model.SkuInstance;
import com.gitee.qdbp.vmall.sales.biz.goods.main.basic.GoodsVersionBasic;
import com.gitee.qdbp.vmall.sales.biz.goods.manage.basic.ShoppingCartBasic;
import com.gitee.qdbp.vmall.sales.enums.GoodsState;
import com.gitee.qdbp.vmall.sales.enums.MallScene;
import com.gitee.qdbp.vmall.sales.error.MallErrorCode;

/**
 * 用户购物车业务处理类
 *
 * @author zhh
 * @version 180703
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
public class ShoppingCartExecutor implements IShoppingCartExecutor {

    /** 日志对象 **/
    private static final Logger log = LoggerFactory.getLogger(ShoppingCartExecutor.class);

    @Autowired
    private ShoppingCartBasic shoppingCartBasic;
    @Autowired
    private GoodsVersionBasic goodsVersionBasic;
    @Autowired
    private ISimpleTreeQueryer simpleTreeQueryer;

    @Override
    public void create(String userId, ShoppingGoodsItem params, IAccount me) throws ServiceException {
        String msg = "Failed to create ShoppingCart. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(params)) {
            log.error(msg + "params is null: params");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        String goodsVid = params.getGoodsVid();
        if (VerifyTools.isBlank(goodsVid)) {
            log.error(msg + "params is null: GoodsVid");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        GoodsVersionBean goods;
        { // 查询商品信息
            goods = goodsVersionBasic.findByVid(goodsVid);
            if (goods == null) {
                log.error(msg + "goods not found: GoodsVid={}", goodsVid);
                throw new ServiceException(MallErrorCode.GOODS_RECORD_NOT_FOUND);
            }
            if (goods.getGoodsState() != GoodsState.SELLING) {
                log.error(msg + "goods was not selling: GoodsVid={}", goodsVid);
                throw new ServiceException(MallErrorCode.GOODS_ALREADY_EXPIRED);
            }
        }
        // 检查商品及单品参数
        int codeLength = ISimpleTreeQueryer.CATEGORY_CODE_LENGTH;
        String skuId = params.getSkuId();
        List<SkuInstance> skuData = goods.getSkuInstanceData();
        if (VerifyTools.isNotBlank(skuData)) {
            if (VerifyTools.isBlank(skuId)) { // 复合商品必须指定一个单品
                log.error(msg + "SkuId is null, GoodsVid={}", goods.getVid());
                throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
            } else {
                SkuInstance sku = null;
                for (SkuInstance temp : skuData) {
                    if (skuId.equals(temp.getId())) {
                        sku = temp;
                        break;
                    }
                }
                if (sku == null) {
                    log.error(msg + "SkuId[{}] not found, GoodsVid={}", skuId, goods.getVid());
                    throw new ServiceException(ResultCode.PARAMETER_VALUE_ERROR);
                }
            }
        }

        ShoppingCartBean older;
        { // 查询数据是否存在
            ShoppingCartWhere w = new ShoppingCartWhere();
            w.setTenantCode(params.getTenantCode()); // 商家租户编号 
            w.setUserId(userId); // 消费者用户ID
            if (VerifyTools.isBlank(skuData)) { // 单一商品
                w.setSkuId(goods.getUid()); // 单品ID
            } else { // 复合商品
                w.setSkuId(params.getSkuId()); // 单品ID
            }
            older = shoppingCartBasic.find(w);
        }
        if (older == null) { // 数据不存在
            ShoppingCartBean model = new ShoppingCartBean();
            model.setTenantCode(params.getTenantCode()); // 商家租户编号
            model.setUserId(userId); // 消费者用户ID
            model.setGoodsUid(goods.getUid()); // 商品唯一ID
            model.setGoodsVid(goods.getVid()); // 商品版本ID
            model.setQuantity(params.getQuantity()); // 购买数量
            model.setChecked(true); // 是否选中
            if (VerifyTools.isBlank(skuData)) { // 单一商品
                model.setSkuId(goods.getUid()); // 单品ID
            } else { // 复合商品
                model.setSkuId(params.getSkuId()); // 单品ID
            }
            KeywordHandler keywords = KeywordHandler.newInstance();
            keywords.addSegment(goods.getQueryKeywords());
            // 获取品牌名称作为查询关键字
            if (VerifyTools.isNotBlank(goods.getBrandCode())) {
                List<String> brandCodes = CodeTools.split(goods.getBrandCode(), codeLength, true);
                String brandScene = MallScene.GOODS_BRAND.name();
                List<SimpleTreeBean> brands = simpleTreeQueryer.list(brandScene, brandCodes, true);
                for (SimpleTreeBean brand : brands) {
                    keywords.addPlain(brand.getNodeText());
                }
            }
            model.setQueryKeywords(keywords.toString());

            // 向vml_shopping_cart表插入记录
            shoppingCartBasic.create(model);
        } else { // 数据已经存在
            ShoppingCartUpdate ud = new ShoppingCartUpdate();
            ud.setGoodsVid(goodsVid); // 商品版本ID
            // ud.setGoodsUid(model.getGoodsUid()); // 商品唯一ID
            ud.setQuantityAdd(params.getQuantity()); // 购买数量
            // ud.setQueryKeywords(model.getQueryKeywords()); // 查询关键字
            ud.setCreateTime(new Date()); // 创建时间修改为当前时间
            ud.setChecked(true); // 是否选中
            ShoppingCartWhere w = ud.getWhere(true);
            w.setId(older.getId());
            shoppingCartBasic.update(ud, true);
        }
    }

    @Override
    public void updateQuantityById(String shoppingCartId, int quantity, IAccount me) throws ServiceException {
        String msg = "Failed to update ShoppingCartItemQuantity. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(shoppingCartId)) {
            log.error(msg + "params is null: shoppingCartId");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (quantity <= 0) {
            log.error(msg + "params quantity must be greater than 0: quantity={}", quantity);
            throw new ServiceException(ResultCode.PARAMETER_VALUE_ERROR);
        }

        ShoppingCartUpdate ud = new ShoppingCartUpdate();
        ud.setQuantity(quantity);
        ud.setChecked(true);
        ShoppingCartWhere w = ud.getWhere(true);
        w.setId(shoppingCartId);

        // 更新vml_shopping_cart表的记录
        shoppingCartBasic.update(ud, false);
    }

    @Override
    public void updateCheckedById(String shoppingCartId, boolean checked, IAccount me) throws ServiceException {
        String msg = "Failed to update ShoppingCartItemChecked. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(shoppingCartId)) {
            log.error(msg + "params is null: shoppingCartId");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        ShoppingCartUpdate ud = new ShoppingCartUpdate();
        ud.setChecked(checked);
        ShoppingCartWhere w = ud.getWhere(true);
        w.setId(shoppingCartId);

        // 更新vml_shopping_cart表的记录
        shoppingCartBasic.update(ud, false);
    }

    @Override
    public void updateCheckedByUser(String userId, boolean checked, IAccount me) throws ServiceException {
        String msg = "Failed to update ShoppingCartItemChecked. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(userId)) {
            log.error(msg + "params is null: userId");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        ShoppingCartUpdate ud = new ShoppingCartUpdate();
        ud.setChecked(checked);
        ShoppingCartWhere w = ud.getWhere(true);
        w.setUserId(userId);

        // 更新vml_shopping_cart表的记录
        shoppingCartBasic.update(ud, false);
    }

    @Override
    public void deleteById(String shoppingCartId, IAccount me) throws ServiceException {
        String msg = "Failed to delete ShoppingCart. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(shoppingCartId)) {
            log.error(msg + "params is null: shoppingCartId");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        ShoppingCartWhere w = new ShoppingCartWhere();
        w.setId(shoppingCartId);
        // 删除vml_shopping_cart表的记录
        shoppingCartBasic.deleteByIds(Arrays.asList(shoppingCartId), false);
    }

    @Override
    public void deleteById(List<String> shoppingCartIds, IAccount me) throws ServiceException {
        String msg = "Failed to delete ShoppingCart. ";

        if (VerifyTools.isBlank(me)) {
            log.error(msg + "params is null: me");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }
        if (VerifyTools.isBlank(shoppingCartIds)) {
            log.error(msg + "params is null: shoppingCartIds");
            throw new ServiceException(ResultCode.PARAMETER_IS_REQUIRED);
        }

        // 删除vml_shopping_cart表的记录
        shoppingCartBasic.deleteByIds(shoppingCartIds, false);
    }

}
